import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
import module from "./module";
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home/index.vue'),
    meta:{
        requireAuth:true,//当有这个字段的时候，我们就认为这个路由页面是要有登录权限的
    },
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/login.vue')
  },
  {
    path: '/classify',
    name: 'Classify',
    component: () => import('@/views/Classify'),
    meta:{
        requireAuth:true,//当有这个字段的时候，我们就认为这个路由页面是要有登录权限的
    },
  },
  {
      path: '/shoppingCart',
      name: 'ShoppingCart',
      component: () => import('@/views/ShoppingCart'),
      meta:{
          requireAuth:true,//当有这个字段的时候，我们就认为这个路由页面是要有登录权限的
      },
  },
  ...module
]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
      if (localStorage.getItem("token")&&localStorage.getItem("token")!=='undefined') {  // 通过vuex state获取当前的token是否存在
        store.commit('settoken',localStorage.getItem("token"))
          next();
      }
      else {
          next({
              path: '/login',
              query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
          })
      }
  }
  else {
      next();
  }
})
export default router
